package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.example.common.AutoLog;
import com.example.common.CaptureConfig;
import com.example.common.Result;
import com.example.entity.Admin;
import com.example.entity.Paper;
import com.example.entity.Params;
import com.example.service.AdminService;
import com.github.pagehelper.PageInfo;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;

    @GetMapping
    public Result findAll(){
        List<Admin> list = adminService.findAll();
        return Result.success(list);
    }

    @PostMapping("/login")
    @AutoLog("用户登录")
    public Result login(@RequestBody Admin admin, @RequestParam String key){
        if(admin.getVerCode()!=null&&!admin.getVerCode().toLowerCase().equals(CaptureConfig.CAPTURE_MAP.get(key))){
            return Result.error("验证码不正确");
        }
        CaptureConfig.CAPTURE_MAP.remove(key);
        Admin loginUser = adminService.login(admin);
        return Result.success(loginUser);
    }

    @PostMapping("/register")
    public Result register(@RequestBody Admin admin){
        adminService.add(admin);
        return Result.success();
    }

    @GetMapping("/search")
    public Result findBySearch(Params params){
        PageInfo<Admin> info = adminService.findBySearch(params);
        return Result.success(info);
    }

    @PostMapping
    @AutoLog("增改用户")
    public Result save(@RequestBody Admin admin){
        if(admin.getId()==null){
            adminService.add(admin);
        }else{
            adminService.update(admin);
        }
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @AutoLog("删除用户")
    public Result delete(@PathVariable Integer id){
        adminService.delete(id);
        return Result.success();
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        List<Admin> infoList = ExcelUtil.getReader(file.getInputStream()).readAll(Admin.class);
        if(!CollectionUtil.isEmpty(infoList)){
            for(Admin admin: infoList){
                try{
                    adminService.add(admin);
                }catch (Exception e){

                    e.printStackTrace();
                }
            }
        }
        return Result.success();
    }
}
